﻿using Tszy.Unlimited.Base.Common;

namespace Tszy.Unlimited.Base.Infrastructure.Stores;

/// <summary>
/// 拥有范围限制的存储器。
/// </summary>
public class DefaultScopeStore : IScopeStore
{
    private readonly IDictionary<string, object> _sotre = new Dictionary<string, object>();

    /// <summary>
    /// 初始化。
    /// </summary>
    public DefaultScopeStore()
    {
        UniqueId = IdentityGenerator.NewSequentialGuid();
    }

    /// <summary>
    /// 唯一标识。
    /// </summary>
    public Guid UniqueId { get; }

    /// <summary>
    /// 获得数据。
    /// </summary>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    /// <exception cref="ScopeStoreException"></exception>
    public TValue Get<TValue>(string key)
    {
        if (_sotre.ContainsKey(key))
            return (TValue)_sotre[key];

        throw new ScopeStoreException("key 已存在");
    }

    /// <summary>
    /// 获得所有数据。
    /// </summary>
    /// <returns></returns>
    public IEnumerable<object> GetAll() => _sotre.Values;

    /// <summary>
    /// 保存数据。
    /// </summary>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="overlay"></param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <exception cref="ScopeStoreException"></exception>
    public void Save<TValue>(string key, TValue value, bool overlay = true)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        if (_sotre.ContainsKey(key))
        {
            if (overlay)
            {
                _sotre[key] = value;
            }
            else
                throw new ScopeStoreException("key 已存在");
        }
        else
            _sotre.Add(key, value);
    }
}